//index.js
//获取应用实例
const app = getApp()
const call = require('../../utils/request.js');
const util = require('../../utils/util.js');
const md5 = require('../../utils/md5.js');
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    loading: true,
    showModalStatus: false
  },
  //事件处理函数
  onAccess: function(e) { //授权按钮
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onEnterManager() { //进入食材管家
    //生成加载框
    wx.showLoading({
      title: '正在获取食材...',
    })
    let that = this;
    if (app.globalData.mac) { //如果存在mac
      wx.navigateTo({
        url: '../foodmanager/foodmanager'
      })
    } else {
      console.log('你需要获取mac')
      that._getMac();//获取冰箱的mac
    }
  },
  //以下是生命周期函数以及私有函数
  onLoad: function() {

  },
  onShow() { //生命周期onShow
    this._PermissionCheck();
  },
  _PermissionCheck() {
    var that = this;
    wx.getUserInfo({
      success(res) {
        app.globalData.userInfo = res.userInfo
        //判断登录状态
        that._getUser();
          if (app.globalData.phoneNumber) {
            if(app.globalData.mac){
              //一切就绪
              console.log('app.globalData.mac', app.globalData.mac);
              app.globalData.reqHeader = {
                "timestamp": util.dataFormat().time2,
                "deviceCode": app.globalData.mac,
                "ver": "v1.0",
                "sign": md5.hexMD5(`timestamp:${util.dataFormat().time2},deviceCode:${app.globalData.mac},ver:v1.0,unilife`)
              }
            }else{
              that._getMac();//获取冰箱的mac
            }
          } else {
            that._getOpenId(); //获取openId去得到手机号
          }
      },
      fail() {
        //弹出权限授权
        console.log('获取授权失败')
        that.setData({
          showModalStatus: true
        })
      }
    })
  },
  handleShow(e) {
    console.log('允许的回调', e)
    var id = e.detail.tag;
    console.log(id)
  },
  _permit(e) {
    console.log('cc', e)
    const show1 = e.detail.showModalStatus;
    this.setData({
      showModalStatus: show1
    })
    if (!show1) {
      console.log('同意');
      this._PermissionCheck()
    }
  },
  _getUser() { //获取用户信息
    let that = this;
    that.setData({
      userInfo: app.globalData.userInfo
    }, () => {
      wx.getStorage({
        key: 'log',
        success: function(res) {
          wx.navigateTo({
            url: '../login/login',
          });
        }
      })
    })
  },
  _getOpenId() { //获取openId
    let that = this;
    wx.login({
      success(reslogin) {
        if (reslogin.code) {
          wx.getUserInfo({
            success(res) {
              const url = '/service/app/v1/account/decodeWxUserInfo'; //根据encryptedData,iv,code获取openId
              const params = {
                "data": {
                  'encryptedData': res.encryptedData,
                  'iv': res.iv,
                  'code': reslogin.code
                }
              }
              call.postData(url, params,
                res => {
                  app.globalData.openId = res.data.openId;
                  that._getPhoneNumber();
                },
                err => {
                  wx.showToast({
                    title: '获取openId失败',
                    icon: 'none'
                  })
                  console.log('获取openId失败', err)
                })
            },
            fail() {
              wx.showToast({
                title: '无法获取用户信息2',
                icon: 'none'
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          })
        }
      }
    })
  },
  _getPhoneNumber() { //根据openId获取用户手机号码
    let that = this;
    const url = `/service/app/v1/account/loginByOpenId`;
    const params = {
      "header": {},
      "data": {
        "openId": app.globalData.openId
      }
    };
    call.postData(url, params,
      res => {
        if (res.data.cellphone) { //已绑定手机号的用户
          console.log('获取手机号接口成功', res);
          console.log('手机号为：', res.data.cellphone)
          app.globalData.phoneNumber = res.data.cellphone;
          that._getMac();//获取冰箱的mac
        } else { //未绑定手机号的用户
          wx.setStorage({
            key: 'log',
            data: 'true',
          })
          wx.navigateTo({
            url: '../login/login',
          });
        }
      },
      err => {
        console.log('获取手机号接口失败', err)
      })
  },
  _getMac() {
    const url = `/service/app/v1/account/getUserBindDeviceInfo?access_token=${app.globalData.access_token}`;
    const params = {
      "data": {
        "cellphone": app.globalData.phoneNumber
      }
    };
    call.postData(url, params, res => {
      console.log('获取mac接口调通', res);
      if (res.data) {
        app.globalData.mac = res.data.deviceCode;
        console.log('您的设备号为:', res.data.deviceCode);
        console.log('app.globalData.mac', app.globalData.mac);
      } else {
        console.log('您的测试设备号为:', 'unilife' + app.globalData.phoneNumber);
        wx.hideLoading() //隐藏加载框
        app.globalData.mac = 'unilife' + app.globalData.phoneNumber
      }
    }, err => {
      console.log('调用用户mac接口失败', err);
      wx.showToast({
        title: '网络好像出小差了，获取mac失败',
        icon:'none'
      })
    });
  }
})